import { createRouter, createWebHashHistory } from 'vue-router'
import { routes as screenRoutes } from '@/router/screen.js'
import { useUserStore } from '@/store/user'

const layoutModules = import.meta.glob('../components/layout.vue')
const viewsModules = import.meta.glob('../views/**/*.{vue,jsx}')
const dynamicViewsModules = Object.assign(
  {},
  { ...layoutModules },
  { ...viewsModules },
)

const whiteList = ['/login', '/register', '/404', '/test'] // 白名单

const routes = [
  // 后台系统
  // {
  //   name: 'manager',
  //   path: '/',
  //   component: () => import('@/views/manager/Layout/index.vue'),
  //   // redirect: '/home',
  // },
  // 大屏
  ...screenRoutes,
  // 非权限路由
  {
    name: 'login',
    path: '/login',
    component: () => import('@/views/login.vue'),
  },
  // 系统特殊路由
  {
    name: '404',
    path: '/404',
    component: () => import('@/views/404.vue'),
  },
  {
    name: 'test',
    path: '/test',
    component: () => import('@/views/test.vue'),
  },
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
})

// 判断是否已加载过API路由，防止刷新页面后动态路由被清除
var dynamicCreateRoute = false
// router.beforeEach(async (to, from, next) => {
//   const userStore = useUserStore()

//   // 已登陆且url导向了登录页，则重定向至首页
//   if (userStore.token && to.path === '/login') {
//     next('/')
//     return
//   }
//   // 未登录，放行白名单
//   if (!userStore.token) {
//     whiteList.indexOf(to.path) !== -1
//       ? next()
//       : next(`/login?redirect=${to.path}`)
//     return
//   }

//   //加载API路由
//   if (!userStore.dynamicCreateRoute || !dynamicCreateRoute) {
//     if (!userStore.dynamicCreateRoute) {
//       const allRoutes = router.getRoutes()
//       allRoutes.forEach((item) => {
//         if (routes.findIndex((i) => i.name === item.name) === -1) {
//           router.removeRoute(item.name)
//         }
//       })
//     }
//     dynamicCreateRoute = true
//     userStore.setDynamicCreateRoute(true)
//     const routeAuth = filterAsyncRouter(userStore.menu)
//     if (routeAuth.length === 0) {
//       next('/')
//       return
//     }
//     const managerRoute = {
//       name: 'manager',
//       path: '/',
//       component: () => import('@/views/manager/Layout/index.vue'),
//       redirect: routeAuth[0].path,
//       children: routeAuth,
//     }
//     router.addRoute(managerRoute)
//     // routeAuth.forEach((menu) => {
//     //   if (!router.hasRoute(menu.name)) {
//     //     router.addRoute('manager', menu)
//     //   }
//     // })
//     // if (to.fullPath === '/') {
//     //   next(routeAuth[0].path)
//     // } else {
//     next({ ...to, replace: true })
//     // }
//   } else {
//     next()
//   }

//   // 必须有，否则访问不存在路由不会跳转404
//   if (!router.hasRoute('redirect404')) {
//     router.addRoute({
//       path: '/:pathMatch(.*)*',
//       name: 'redirect404',
//       redirect: '/404',
//     })
//   }
// })

// 转换
function filterAsyncRouter(routerMap) {
  const accessedRouters = []
  routerMap.forEach((item) => {
    const route = {
      path: item.routePath,
      name: item.code,
      meta: { title: item.catalogName, show: item.showStatus },
      redirect: getRedirect(item.children),
      children: item.children ? filterAsyncRouter(item.children) : null,
      // component: loadComponent(item.routeModule),
      component: dynamicImport(dynamicViewsModules, item.routeModule),
    }
    accessedRouters.push(route)
  })
  return accessedRouters
}
// 获取组件地址
function loadComponent(component) {
  if (component && component !== 'Layout') {
    return () => import(/* @vite-ignore */ `../views${component}`)
  } else {
    return () => import(`@/components/layout.vue`)
  }
}

function getRedirect(children) {
  if (children && children.length > 0) {
    return children[0].routePath
  } else {
    return ''
  }
}

function dynamicImport(dynamicViewsModules, component) {
  const keys = Object.keys(dynamicViewsModules)
  const matchKeys = keys.filter((key) => {
    const k = key.replace(/..\/views|../, '')
    return k.startsWith(`${component}`) || k.startsWith(`/${component}`)
  })
  if (matchKeys?.length === 1) {
    const matchKey = matchKeys[0]
    return dynamicViewsModules[matchKey]
  }
  if (matchKeys?.length > 1) {
    return false
  }
}

export default router
